package org.jinyan.led.tcp;

import java.nio.channels.SocketChannel;
import java.util.HashMap;

import org.jinyan.led.model.ClientSocket;

public class ClientSocketManager {
	private static HashMap<String, ClientSocket> cacheMap = new HashMap<String, ClientSocket>();

	private ClientSocketManager() {

	}

	public static synchronized void putClientSocket(String key, ClientSocket obj) {
		if (!cacheMap.containsKey(key)) {
			cacheMap.put(key, obj);
			System.out.println("添加:" + obj);
		}

	}

	public static synchronized ClientSocket getClientSocket(String key) {
		if (cacheMap.containsKey(key)) {
			System.out.println("获取:" + cacheMap.get(key));
			return cacheMap.get(key);
		} else {
			return null;
		}
	}

	public static synchronized ClientSocket clearClientSocket(SocketChannel sc) {
		System.out.println("clearClientSocket sc start");
		String key=null;
		for (String element : cacheMap.keySet()) {
			ClientSocket client = cacheMap.get(element);
			if(sc==client.getSocketChannel()){
				key=element;
			}
			
		}
		if (key!=null&&cacheMap.containsKey(key)) {
			System.out.println("clearClientSocket sc end success");
			return cacheMap.remove(key);
		} else {
			System.out.println("clearClientSocket sc end fail");
			return null;
		}
	}
	public static synchronized ClientSocket clearClientSocket(String key) {
		if (cacheMap.containsKey(key)) {
			return cacheMap.remove(key);
		} else {
			return null;
		}
	}

	public static synchronized void clearAllClientSocket() {
		if (!cacheMap.isEmpty()) {
			cacheMap.clear();
		}
	}

}
